package com.allwees.bs.module.wms.service.impl;

import com.allwees.bs.core.modelbase.entity.WfBaseEntity;
import com.allwees.bs.module.base.service.impl.BoServiceImpl;
import com.allwees.bs.module.wms.dao.WmsPickOrderSkuDao;
import com.allwees.bs.module.wms.entity.WmsAllocateOrderSku;
import com.allwees.bs.module.wms.entity.WmsPickOrderSku;
import com.allwees.bs.module.wms.mq.event.PlatformShippedMqEvent;
import com.allwees.bs.module.wms.service.WmsPickOrderSkuService;
import com.allwees.core.common.constant.EStatus;
import com.allwees.core.common.util.reflect.PojoUtil;
import com.allwees.core.mq.rabbitmq.MqUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * wms 拣货单
 *
 * @author mouhn
 * @since 2020-01-08 13:56
 */
@Service
public class WmsPickOrderSkuServiceImpl extends BoServiceImpl<WmsPickOrderSkuDao, WmsPickOrderSku> implements WmsPickOrderSkuService {

    @Override
    @Transactional
    public boolean create(String pickOrderUuid, WmsAllocateOrderSku allocateOrderSku) {
        WmsPickOrderSku pickOrderSku = PojoUtil.copyWithOmit(new WmsPickOrderSku(), allocateOrderSku, WfBaseEntity.fields);
        pickOrderSku.setEStatus(EStatus.WMS_WAIT_PICK);
        pickOrderSku.setPickOrderUuid(pickOrderUuid);
        return create(pickOrderSku);
    }

    @Override
    public List<WmsPickOrderSku> shipping(Set<String> pickOrderSkuUuids) {

        List<WmsPickOrderSku> pickOrderSkus = findByUuids(pickOrderSkuUuids);
        pickOrderSkus.forEach(o -> {
            o.assertStatus(EStatus.WMS_PICKING, EStatus.WMS_WAIT_PICK);

            WmsPickOrderSku update = new WmsPickOrderSku(o.getUuid());
            update.setEStatus(EStatus.WMS_PICKED);
            updateByUuid(update);
        });


        Set<String> orderUuids = pickOrderSkus.stream().map(WmsPickOrderSku::getOrderUuid).collect(Collectors.toSet());
        MqUtil.send(new PlatformShippedMqEvent(orderUuids));

        return pickOrderSkus;
    }

    @Override
    public boolean allShipped(String pickOrderUuid) {
        Integer allCount = baseMapper.findCountByPickOrderUuid(pickOrderUuid);
        Integer statusCount = baseMapper.findCountByPickOrderUuid(pickOrderUuid, EStatus.WMS_SHIPPED);
        return allCount.equals(statusCount);
    }

    @Override
    public void refund(String uuid) {

    }
}
